import cv2
import numpy as np

#-------------轮廓————————————
img = cv2.imread("homework.jpg")  # 读取原图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 彩色图像转为变成单通道灰度图像
t, binary = cv2.threshold(gray, 230, 255, cv2.THRESH_BINARY)  # 灰度图像转为二值图像
# 检测图像中出现的所有轮廓，记录轮廓的每一个点
contours, hierarchy = cv2.findContours(binary,cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
# 绘制所有轮廓，宽度为1，颜色为红色
for contour in contours:
    # print(contour)
    area = cv2.contourArea(contour)
    if area>300:
        cv2.drawContours(img, contour, -1, (0, 0, 255), 2)
        if area > 500:
            # 计算周长作为精度参数
            peri = cv2.arcLength(contour, True)
            # 多边形逼近轮廓  获得边
            vertices = cv2.approxPolyDP(contour, peri * 0.02, True)
            # 统计每个形状的边数
            contsnum = len(vertices)
            # 最大外接矩形 获取（x,y）宽和高
            x, y, w, h = cv2.boundingRect(vertices)

            if contsnum == 3:
                cv2.putText(img, 'Tri', (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1)
                cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
            if contsnum == 4:
                cv2.putText(img, 'Squ', (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1)
                cv2.rectangle(img, (x, y), (x + w, y + h), (124, 25, 110), 2)
            if contsnum == 5:
                cv2.putText(img, '5', (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1)
                cv2.rectangle(img, (x, y), (x + w, y + h), (1, 115, 110), 2)
            if contsnum >= 6:
                cv2.putText(img, 'cir', (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1)
                cv2.rectangle(img, (x, y), (x + w, y + h), (101, 15, 10), 2)

#-------------画出最后结果-----------
cv2.imshow('img',img)
cv2.waitKey()